package servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebInitParam;
import model.DBFacade;


import java.sql.SQLException;
import java.util.*;
import java.io.*;
/**
 * Servlet implementation class Dispatcher
 */
@WebServlet(urlPatterns = { "/Dispatcher" }, initParams = {
		@WebInitParam(name = "jdbcDriver", value = "com.mysql.jdbc.Driver"),
		@WebInitParam(name = "dbUrl", value = "jdbc:mysql://localhost:3306/twitter?useUnicode=true&amp;characterEncoding=UTF-8"),
		@WebInitParam(name = "dbUser", value = "root"),
		@WebInitParam(name = "dbPass", value = "webclass") })
public class Dispatcher extends HttpServlet {
	private static final long serialVersionUID = 1L;
    DBFacade db;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Dispatcher() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		db = new DBFacade();
		db.setDbUrl(config.getInitParameter("dbUrl"));
		db.setDbUser(config.getInitParameter("dbUser"));
		db.setDbPass(config.getInitParameter("dbPass"));
		try {
			Class.forName(config.getInitParameter("jdbcDriver"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		{
			String latitude = request.getParameter("latitude");
			String longitude = request.getParameter("longitude");
			
			System.out.println("db request = " + latitude + ", "+ longitude);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			
			try {
				ArrayList<String> rank = new ArrayList<String>();
				rank = db.getRank(longitude, latitude);
				
//				int i = 1;
				for (int i = 0 ; i < rank.size() ; ++i)
				{
					if (i == 10)
						break;
					
					out.println(rank.get(i));
					if (i < 9)
						out.println("<br>");
					
					System.out.println(rank.get(i) + "<br>");
				}
//				for(String eachRank : rank){
//					out.println(eachRank+"<br>");
////					i++;
//				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			out.close();			
		}
		
	}

}
